package com.example.android.fragments

import android.os.Bundle
import android.text.SpannableStringBuilder
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.example.android.R
import com.example.android.extensions.AlertDialog
import com.example.android.extensions.Services
import com.example.android.models.KeyboardLayout
import com.example.android.models.User
import com.example.android.viewmodels.SharedViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * 功能：订单支付
 *
 * create an instance of this fragment.
 */
class PayDetailFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null
    private var imgbutton: ImageButton? = null
    private var keyboardLayout: KeyboardLayout? = null
    private var password:TextView? = null
    private var pay:Button? = null

    private val _Model : SharedViewModel by activityViewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_pay_detail, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        //加载数字键盘
            password = view.findViewById(R.id.password)
            keyboardLayout = view.findViewById(R.id.keyboard_layout)
            keyboardLayout?.onKeyboardInputListener = object : KeyboardLayout.OnKeyboardInputListener {
                    override fun onKeyboardInput(key: String, isDel: Boolean) {
                        password?.text = if (isDel) {
                            ""
                        } else {
                            password?.text.toString() + key
                        }
                    }
            }


        val spannableStringBuilder = SpannableStringBuilder()
        //设置输入框样式：
//        spannableStringBuilder.setSpan(
//            ShapeSpan(Color.GRAY, 20 * resources.displayMetrics.density).apply {
//            paddingLeft = (6 * resources.displayMetrics.density).toInt()
//            paddingRight = paddingLeft
//            paddingTop = paddingLeft / 2
//            paddingBottom = paddingTop
//
//            marginLeft = (4 * resources.displayMetrics.density).toInt()
//            marginRight = marginLeft
//            marginTop = marginLeft / 2
//            marginBottom = marginTop
//
//            textColor = Color.RED
//        },
//            3, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

            password?.text = spannableStringBuilder

        //支付提醒
        imgbutton = view.findViewById(R.id.back)
        imgbutton?.setOnClickListener {
            val back = OnlinePaymentFragment()
            requireActivity().supportFragmentManager
                .beginTransaction()
                .setCustomAnimations(
                    R.anim.fragment_item_select_in,
                    R.anim.fragment_item_select_out,
                    R.anim.fragment_item_back_in,
                    R.anim.fragment_item_back_out)
                .replace(R.id.content_main_fragment, back)
                .addToBackStack(null)
                .commit()

            AlertDialog {
                it.SetTitle("支付失败!")
                it.SetContent("订单已取消，请重新支付！")
                it.SetOnSureButton {
                    it.dismiss()
                }
                it.SetOnCancelButton {
                    it.dismiss()
                }
            }

        }

        pay=view.findViewById(R.id.btn_confirm_pay)
        pay?.setOnClickListener{
            AlertDialog {
                it.SetTitle("请确认支付")
                it.SetContent("请仔细核对订单\n总共支付学费：9640元\n确认订单后请点击确认键完成支付")
                it.SetOnSureButton {
                    it.dismiss()
                    val back = OnlinePaymentFragment()
                    requireActivity().supportFragmentManager
                        .beginTransaction()
                        .setCustomAnimations(
                            R.anim.fragment_item_select_in,
                            R.anim.fragment_item_select_out,
                            R.anim.fragment_item_back_in,
                            R.anim.fragment_item_back_out)
                        .replace(R.id.content_main_fragment, back)
                        .addToBackStack(null)
                        .commit()

                    lifecycleScope.launch(Dispatchers.Main) {
                        Services.SharedService.GetSelfInfo(_Model)
                        Services.PayService.confirm(_Model.getSelf().value!!)
                    }

                    AlertDialog {
                        it.SetContent("恭喜你完成入学缴费！")
                        it.SetOnSureButton {
                            it.dismiss()
                        }
                    }
                }
                it.SetOnCancelButton {
                    it.dismiss()
                }
            }
        }

    }



    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment PayDetailFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            PayDetailFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}